<template>
  <div class="customer-management">
    <el-form
      :model="form"
      :inline="true"
      class="form-container"
      style="width: 1500px"
    >
      <el-form-item label="客户编号" prop="customernumber">
        <el-input v-model="form.customerId" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item label="客户名称" prop="customerName">
        <el-input v-model="form.customerName" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item label="电话" prop="phone">
        <el-input v-model="form.phone" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="Getcustomer">查询</el-button>
        <el-button @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
    <div class="button-container">
      <el-button type="primary">新增</el-button>
      <el-button @click="handleEdit">编辑</el-button>
      <el-button
        type="danger"
        @click="handleDelete('批量删除')"
        :disabled="selectedRows.length === 0"
        >批量删除</el-button
      >
      <el-button @click="handleRefresh">刷新</el-button>
      <el-button @click="handleExport">导出</el-button>
    </div>
    <el-table
      @selection-change="handleSelectionChange"
      :data="tableData"
      border
      style="width: 1500px"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column label="编号" prop="customerId"></el-table-column>
      <el-table-column label="客户编号" prop="customernumber"></el-table-column>
      <el-table-column label="客户名称" prop="customerName"></el-table-column>
      <el-table-column label="地址" prop="address"></el-table-column>
      <el-table-column label="电话" prop="phone"></el-table-column>
      <el-table-column label="传真" prop="fax"></el-table-column>
      <el-table-column label="Email" prop="email"></el-table-column>
      <el-table-column label="联系人" prop="contactPerson"></el-table-column>
      <el-table-column v-slot="scoped" label="创建时间" prop="">
        {{ scoped.row.creationTime.substring(0, 10) }}
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row.customerId)"
            >编辑</el-button
          >
          <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.row.customerId, [scope.row.customerId])"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="demo-pagination-block">
      <el-pagination
        v-model:current-page="form1.PageIndex"
        v-model:page-size="form1.PageSize"
        :page-sizes="[1, 3, 15, 100]"
        :size="size"
        :disabled="disabled"
        :background="background"
        layout="total, sizes, prev, pager, next, jumper"
        :total="form1.TotalCount"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ElMessageBox, ElTable, ElMessage } from "element-plus";
import { reactive, onMounted, ref } from "vue";
import axios from "axios";
import { Plus } from "@element-plus/icons-vue";
import { useRouter, useRoute } from "vue-router";
import dayjs from "dayjs";
import { KongaUrl } from "@/axios/axiosHelp";
const router = useRouter();
// 客户表单数据
const AddConact = ref([
  {
    contactId: 0,
    contactPerson: "",
    address: "",
    contactPhone: "",
    CreationTime: "2023-11-20",
    isDelete: false,
    isEdit: false,
  },
]);

const addContact = () => {
  customerForm.contacts.push(createEmptyContact());
};
// 创建空联系人模板
function createEmptyContact() {
  return {
    contactId: 0,
    contactPerson: "",
    address: "",
    contactPhone: "",
    creationTime: dayjs().format("YYYY-MM-DD"), // 格式化日期时间
    isDelete: false,
  };
}
const handleBatchAdd = async () => {
  try {
    // 调用API
    const response = await KongaUrl.post(
      "/wantgcong1/api/WHouase/AddContactsWithCustomer",
      customerForm
    );

    if (response.data.code === 200) {
      ElMessage.success("添加成功");
      // 重置表单
    } else {
      ElMessage.error(response.data.message);
    }
  } catch (error) {
    ElMessage.error("请求失败: ");
  }
};
const removeContact = (index:any) => {
  ElMessageBox.confirm("是否确认删除?", "提示", {
    confirmButtonText: "是",
    cancelButtonText: "否",
    type: "warning",
  }).then(() => {
    customerForm.contacts.splice(index, 1);
  });
};
// 表单数据
const form = reactive({
  customernumber: "",
  customerName: "",
  phone: "",
});
const form1 = reactive({
  TotalCount: 0,
  PageCount: 0,
  PageSize: 15,
  PageIndex: 1,
});
// 表格数据（测试数据）
const tableData = ref([]);
const Getcustomer = () => {
  KongaUrl.get("/wangcong/api/Whouase/GetCustomer", {
    params: {
      PageSize: form1.PageSize,
      PageIndex: form1.PageIndex,
      Customernumber: form.customernumber,
      CustomerName: form.customerName,
      Phone: form.phone,
    },
  })
    .then((res) => {
      tableData.value = res.data.data.list;
      form1.TotalCount = res.data.data.totalCount;
      form1.PageCount = res.data.data.pageCount;
    })
    .catch((error) => {
      ElMessage.error(`获取数据失败: ${error.message}`);
    });
};
//#region 分页
const handleSizeChange = (newSize:any) => {
  form1.PageSize = newSize;
  Getcustomer();
};

const handleCurrentChange = (newPage:any) => {
  form1.PageIndex = newPage;
  Getcustomer();
};
// 查询方法
const query = () => {
  // 这里可以添加实际的查询逻辑，比如调用后端接口
  console.log("执行查询操作", form.value);
};

// 重置方法
const reset = () => {
  form.customernumber = "";
  form.customerName = "";
  form.phone = "";
};
// 编辑方法
const dialogVisible = ref(false);
const customerForm = reactive({
  customerId: 0,
  Customernumber: "",
  CustomerName: "",
  Fax: "",
  Phone: "",
  Email: "",
  Remarks: "",
  contacts: [createEmptyContact()], // 初始化一个空联系人,
});
interface Contact {
  contactId: number;
  contactPerson: string;
  address: string;
  contactPhone: string;
  creationTime: string;
}
const handleEdit = (customerId: any) => {
  router.push({
    path: "/UpdateCustomer",
    query: {
      customerId: customerId,
    },
  });

  // if (Object.keys(row).length === 0) {
  //   ElMessage.warning("请选择要编辑的客户");
  //   return;
  // }
  // // 反填数据
  // customerForm.customerId = row.customerId;
  // customerForm.Customernumber = row.customernumber;
  // customerForm.CustomerName = row.customerName;
  // customerForm.Fax = row.fax;
  // customerForm.Phone = row.phone;
  // customerForm.Email = row.email;
  // customerForm.Remarks = row.remarks;
  // // 处理联系人数据反填
  // if (Array.isArray(row.contacts) && row.contacts.length > 0) {
  //   customerForm.contacts = [];
  //   row.contacts.forEach((contact) => {
  //     const newContact = {
  //       contactId: contact.contactId,
  //       contactPerson: contact.contactPerson,
  //       address: contact.address,
  //       contactPhone: contact.contactPhone,
  //       creationTime: contact.creationTime,
  //     };
  //     customerForm.contacts.push(newContact);
  //   });
  // } else {
  //   customerForm.contacts = [createEmptyContact()];
  // }
  // dialogVisible.value = true;
const handleEdit = (customerId: any) => {
  router.push({
    path: "/UpdateCustomer",
    query: {
      customerId: customerId,
    },
  });

  // if (Object.keys(row).length === 0) {
  //   ElMessage.warning("请选择要编辑的客户");
  //   return;
  // }
  // // 反填数据
  // customerForm.customerId = row.customerId;
  // customerForm.Customernumber = row.customernumber;
  // customerForm.CustomerName = row.customerName;
  // customerForm.Fax = row.fax;
  // customerForm.Phone = row.phone;
  // customerForm.Email = row.email;
  // customerForm.Remarks = row.remarks;
  // // 处理联系人数据反填
  // if (Array.isArray(row.contacts) && row.contacts.length > 0) {
  //   customerForm.contacts = [];
  //   row.contacts.forEach((contact) => {
  //     const newContact = {
  //       contactId: contact.contactId,
  //       contactPerson: contact.contactPerson,
  //       address: contact.address,
  //       contactPhone: contact.contactPhone,
  //       creationTime: contact.creationTime,
  //     };
  //     customerForm.contacts.push(newContact);
  //   });
  // } else {
  //   customerForm.contacts = [createEmptyContact()];
  // }
  // dialogVisible.value = true;
};
//批量删除
const selectedRows = ref<any[]>([]);
const handleSelectionChange = (val: any[]) => {
  selectedRows.value = val;
};

// 优化后的删除方法
const handleDelete = async (id: any, stockNum: any = []) => {
  try {
    let ids = [];
    let stockNumbers = [];

    if (id === "批量删除") {
      // 批量删除逻辑
      if (selectedRows.value.length === 0) {
        ElMessage.warning("请至少选择一条记录");
        return;
      }
      ids = selectedRows.value.map((item) => item.customerId);
      stockNumbers = selectedRows.value.map((item) => item.customerId);

      await ElMessageBox.confirm(
        `确定要删除${selectedRows.value.length}条记录？`,
        "警告",
        { type: "warning" }
      );
    } else {
      // 单条删除逻辑
      ids = [id];
      stockNumbers = stockNum;

      await ElMessageBox.confirm("确定要删除该记录吗？", "警告", {
        type: "warning",
      });
    }

    // 统一请求处理
    const params = new URLSearchParams();
    params.append("Table", "Customer");
    params.append("TableId", "CustomerId");
    ids.forEach((id:any) => params.append("Ids", id.toString()));
    stockNumbers.forEach((num:any) => params.append("CustomerId", num));

    const res = await KongaUrl.delete(
      "/wangcong1/api/WHouase/DelsConact",
      {
        params: params,
        paramsSerializer: (params) => params.toString(), // 确保参数序列化正确
      }
    );

    if (res.data.code === 500) {
      ElMessage.success(res.data.message);
      Getcustomer();
      if (id === "批量删除") {
        selectedRows.value = []; // 清空选择
      }
    } else {
      ElMessage.error(res.data.message);
    }
  } catch (error) {
    if (error !== "cancel") {
      // 忽略用户取消操作
      ElMessage.error(`操作失败: ${error.message}`);
    }
  }
};
// 删除方法
// const handleDelete = (customerId: any) => {
//   ElMessageBox.confirm("是否确认删除?", "提示", {
//     confirmButtonText: "是",
//     cancelButtonText: "否",
//     type: "warning",
//   }).then(() => {
//     axios
//       .delete("https://localhost:7193/api/WHouase/DeleteConact", {
//         params: {
//           customerId: customerId,
//         },
//       })
//       .then((res) => {
//         if (res.data.code == 500) {
//           ElMessage.success(res.data.message);
//           Getcustomer();
//         } else {
//           ElMessage.error(res.data.message);
//         }
//       });
//   });
// };
// const handleDelete = (customerId: any) => {
//   ElMessageBox.confirm("是否确认删除?", "提示", {
//     confirmButtonText: "是",
//     cancelButtonText: "否",
//     type: "warning",
//   }).then(() => {
//     axios
//       .delete("https://localhost:7193/api/WHouase/DeleteConact", {
//         params: {
//           customerId: customerId,
//         },
//       })
//       .then((res) => {
//         if (res.data.code == 500) {
//           ElMessage.success(res.data.message);
//           Getcustomer();
//         } else {
//           ElMessage.error(res.data.message);
//         }
//       });
//   });
// };

// 刷新方法
const handleRefresh = () => {
  ElMessage.success("执行刷新操作");
  Getcustomer();
};

// 导出方法
// 导出方法
const handleExport = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请选择要导出的客户");
    return;
  }

  // 构造后端所需参数（包含选中ID及查询条件）
  const exportParams = {
    Ids: selectedRows.value.join(","), // 选中ID转字符串（根据后端接口要求调整格式）
    PageIndex: form1.PageIndex,
    PageSize: form1.PageSize,
    Customernumber: form.customernumber,
    CustomerName: form.customerName,
    Phone: form.phone,
  };

  KongaUrl
    .get("/wangcong/api/Whouase/ExportOrderListToExcel", {
      params: exportParams,
      responseType: "blob", // 处理二进制流
    })
    .then((response) => {
      const blob = new Blob([response.data], {
        type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
      });
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement("a");
      link.href = url;
      link.download = "客户数据.xlsx"; // 自定义文件名
      link.click();
      window.URL.revokeObjectURL(url); // 释放资源
    })
    .catch((error) => {
      ElMessage.error(`导出失败: ${error.message}`);
    });
};
// 更新方法
const handleUpdate = async () => {
  try {
    // 调用API更新数据
    const response = await KongaUrl.put(
      "/wangcong1/api/Whouase/UpdateCustomer",
      customerForm
    );
    if (response.data.code === 200) {
      ElMessage.success("更新成功");
      dialogVisible.value = false;
      Getcustomer();
    } else {
      ElMessage.error(response.data.message);
    }
  } catch (error) {
    ElMessage.error("请求失败: ");
  }
};
onMounted(() => {
  Getcustomer();
});
}
</script>

<style scoped>
.customer-management {
  padding: 20px;
}
.form-container {
  margin-bottom: 15px;
}
.button-container {
  margin-bottom: 15px;
  text-align: right;
}
</style> 